<template>
  <!-- 语音会议 -->
  <div class="audio_meeting">
    <div class="meeting_box">
      <div :class="{'meeting_fl_box':true, fl_slot: rightStatus}">
        <ul class="member_ul">
          <li :class="{m_li: isPhone}" v-for="(item, index) in memberArr" :key="index">
            <span>{{item.name}}</span>
          </li>
        </ul>
        <div id="remoteMedias"></div>
      </div>
      <div :class="{'meeting_fr_box':true, fr_slot: rightStatus}">
        <div class="fr_header">
          <div class="fr_header_fl">{{rHeaderTitle}}</div>
          <img src="../../assets/img/close.png" alt="" @click="rightStatus=false">
        </div>
        <member-list
          :banVideo='true'
          v-show="rightType=='member'"
          :memberArr='memberArr'
        ></member-list>
        <message-list
          :msg='msg'
          :selfName='selfName'
          v-show="rightType=='message'"
        ></message-list>
      </div>
    </div>
    <control-btn
      ref="controlBtn"
      :banVideo='true'
      :banShareScreen='true'
      @showFr="showFr"
      @exitMeeting='exitMeeting'
    ></control-btn>
  </div>
</template>

<script>
import controlBtn from '@/components/meetingControl/index'
import memberList from '@/components/memberList/index'
import messageList from '@/components/messageList/index'

export default {
  name: "audiomeeting",
  data() {
    return {
      h: this.$route.query.h,
      memberArr: [],
      myPeerId: '', // myself id
      isPhone: navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i),
      promptClass: 'pc_prompt',
      selfName: '',
      rightStatus: false,
      rightType: '',
      rHeaderTitle: '',
      interval: null,
      msg: {},
      n: this.$route.query.n || null // 链接上的名字
    };
  },

  components: {
    controlBtn,
    memberList,
    messageList
  },

  created() {
    window.addEventListener('beforeunload', e => this.refreshPage(e))
    this.$once('hook:beforeDestroy', () => {
      window.removeEventListener('beforeunload', e => this.refreshPage(e))
    })
    if (this.isPhone) this.promptClass = 'phone_prompt'
  },

  mounted() {
    this.joinRoom()
  },

  methods: {
    /** 处理微信分享 */
    handleWXShare () {
      if (this.$store.state.functionMap.isWx) {
        this.$WXShare({
          title: '联信UMRTC会议系统',
          desc: `${this.selfName}发起的语音会议`,
          link: location.href,
          imgUrl: location.origin + '/static/img/um.png'
        })
      }
    },
    /** 初始化 */
    initUmVideo () {
      this.umvideo.setup({
        listenPort: this.$store.state.functionMap.listenPort,
        signalServer: this.$store.state.functionMap.signalServer,
        remoteMedias, // 远端音频插入位置
        audio: {
          echoCancellation: true // 回声消除
        }
      })
    },
    /** 加入房间 */
    async joinRoom () {
      if (!await this.$refs.controlBtn.handleSupportStatus()) return

      this.initUmVideo()
      if (this.n) {
        this.handleName(this.n)
      } else {
        this.promptName()
          .then(name => this.handleName(name))
      }
    },
    handleName (name) {
      this.selfName = name
      this.setGlobalSetting('myname', name)
      this.handleWXShare()
      this.handleJoinRoom(name)
    },
    /** 处理加入房间的逻辑 */
    handleJoinRoom (name) {
      this.umvideo.joinRoom(this.h, name, this.$store.state.functionMap.connectType, async (res) => {
        res.roomInfo.peers.map(item => this.memberArr.push({ id: item.id, name: item.name }))
        try {
          await this.umvideo.setMediaEnable(this.umvideo.mediaType.audio, true)
        } catch (error) {
          this.$notify.error({
            title: '提示',
            message: `无法打开本地音频设备${error}`
          })
        }
        [
          'watchRemoteAdd',
          'watchRemoteExit',
          'watchGetMsg',
        ].forEach(v => this[v]())

        this.$refs.controlBtn.handleParentDoFunc()
      })
    },
    /** 监听有人加入 */
    watchRemoteAdd () {
      clearInterval(this.interval)
      this.interval = setInterval(() => {
        document.querySelectorAll('video').forEach(item => item.play())
      }, 1000);
      this.umvideo.on(this.umvideo.EVENTS.addPeer, e => { if (e) this.memberArr = [...this.memberArr, { id: e.id, name: e.name }] })
    },
    /** 监听有人退出 */
    watchRemoteExit () {
      this.umvideo.on(this.umvideo.EVENTS.removePeer, e => {
        if (e) this.memberArr = this.memberArr.filter(item => item.id !== e.id)
      })
    },
    /** 监听收到消息 */
    watchGetMsg () {
      this.umvideo.on(this.umvideo.EVENTS.userMsg, e => this.msg = e)
    },
    /** 弹出来输入名字 */
    promptName () {
      return new Promise(resolve => {
        this.$prompt('请输入姓名', '提示', {
          confirmButtonText: '确定',
          showCancelButton: false,
          showClose: false,
          closeOnPressEscape: false,
          closeOnClickModal: false,
          customClass: this.promptClass,
          inputValue: this.getGlobalSetting('myname') || '',
          beforeClose: (action, instance, done) => {
            if (action === 'confirm' && !instance.inputValue) {
              this.$notify.error({
                title: '提示',
                message: '请输入姓名！'
              })
              return false
            }
            done()
          }
        }).then(({ value }) => {
          resolve(value)
        }).catch(() => {});
      })
    },
    /** 显示成员列表或者消息 */
    showFr (val) {
      this.rightStatus = this.rightType == val ? !this.rightStatus : true
      this.rightType = val
      this.rHeaderTitle = val === 'message' ? '消息' : '成员'
    },
    /** 退出房间 */
    exitMeeting () {
      this.refreshPage()
      this.$router.replace({name: 'roomindex'})
    },
    /** 页面刷新 */
    refreshPage () {
      this.umvideo.exitRoom()
      this.interval && clearInterval(this.interval)
    },
  }
};
</script>

<style lang="scss" scoped>
.audio_meeting {
  height: 100%;
  .meeting_box {
    height: calc(100% - 54px);
    background-color: #2e9cf1;
    display: flex;
    justify-content: space-around;
    .meeting_fl_box {
      width: 100%;
      .member_ul {
        width: 100%;
        height: 100%;
        overflow-y: auto;
        li {
          width: calc(20% - 2px);
          height: 200px;
          border: 1px solid #f7f7f7;
          position: relative;
          display: inline-block;
          border-radius: 5px;
          float: left;
          span {
            color: #fff;
            position: absolute;
            left: 0;
            right: 0;
            bottom: 10px;
            text-align: center;
          }
        }
        .m_li {
          width: calc(50% - 2px);
        }
      }
    }
    .meeting_fr_box {
      height: 100%;
      width: 300px;
      display: none;
      background-color: #fff;
      .fr_header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 15px 20px;
        border-bottom: 1px solid #F0F0F0;
        img {
          cursor: pointer;
        }
      }
    }
    .fl_slot {
      width: calc(100% - 300px);
    }
    .fr_slot {
      display: block;
    }
  }
}
</style>
<style>
.phone_prompt {
  width: 70%;
}
.pc_prompt {
  width: 420px;
}
</style>
